package com.charonmc.commands;

import com.charonmc.CharonLogin;
import com.charonmc.utils.Md5Utils;
import com.charonmc.utils.mysql.SqlManager;
import lombok.SneakyThrows;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

public class ChangePassword implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
        if (sender instanceof Player){
            Player player = (Player) sender;
            if (args.length == 2){
                if (args[0].length() > 20 || args[1].length() > 20) {
                    sender.sendMessage("§c您输入的密码过长");
                    return true;
                } else if (args[0].length() < 6  || args[1].length() < 6) {
                    sender.sendMessage("§c您输入的密码过短");
                    return true;
                } else if (!args[0].equals(args[1])) {
                    sender.sendMessage("§c两个密码不一致！");
                    return true;
                } else if (!Register.isAlphaNumeric(args[0])){
                    sender.sendMessage("§c密码中含有非法字符！");
                    return true;
                } else {
                    BukkitRunnable task = new BukkitRunnable() {
                        @SneakyThrows
                        @Override
                        public void run() {
                            SqlManager sqlManager = new SqlManager("charonmc");
                            sqlManager.createUpdate()
                                    .inTable("players")
                                    .addColumnNames(new String[]{"password"})
                                    .addParams(new Object[]{Md5Utils.getMd5(args[0], player)})
                                    .addCondition("player_name", player.getPlayer().getName())
                                    .build()
                                    .execute();
                            sqlManager.close();
                            sender.sendMessage("§7密码已更改");
                        }
                    };
                    task.runTaskAsynchronously(CharonLogin.instance);
                }
            } else {
                sender.sendMessage("§c参数错误");
                sender.sendMessage("§7使用 §a/cp <新密码> <确认密码> 以修改密码。");
            }

        }
        return true;
    }
}
